package uk.ac.durham.tel.synergynet.covanto.workspace.handler;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.handlers.HandlerUtil;

import uk.ac.durham.tel.synergynet.covanto.project.model.ProjectInfo;
import uk.ac.durham.tel.synergynet.covanto.project.ui.model.ProjectNode;
import uk.ac.durham.tel.synergynet.covanto.workspace.WorkspaceController;
import uk.ac.durham.tel.synergynet.covanto.workspace.WorkspaceException;

public class RemoveProjectHandler extends AbstractHandler implements IHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		ISelection selection = HandlerUtil.getCurrentSelection(event);
		if (!(selection instanceof IStructuredSelection))
			return null;
		IStructuredSelection structSel = (IStructuredSelection) selection;
		List<ProjectInfo> projectsToRemove = new ArrayList<ProjectInfo>();
		for(Iterator<?> i = structSel.iterator(); i.hasNext();) {
			Object element = i.next();
			if (element instanceof ProjectNode) {
				projectsToRemove.add(((ProjectNode) element).getResource());
			}
		}
		deleteProject(projectsToRemove);
		return null;
	}
	
	private boolean deleteProject(final List<ProjectInfo> projectsToRemove) {
		final StringBuilder errorMessages = new StringBuilder();
		try {
			WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
				@Override
				protected void execute(IProgressMonitor monitor)
						throws CoreException, InvocationTargetException,
						InterruptedException {
					monitor.beginTask("Deleting Studies", projectsToRemove.size());
					try {
						for(ProjectInfo projectInfo : projectsToRemove) {
							if(monitor.isCanceled())
								throw new OperationCanceledException("Deleting Study is cancelled.");
							monitor.subTask(String.format("Deleteing %s", projectInfo.getProjectResource().getName()));
							WorkspaceController.getInstance().deleteProject(projectInfo, monitor);
							monitor.worked(1);
						}
					} catch (WorkspaceException e) {
						errorMessages.append(e.getMessage());
						monitor.setCanceled(false);
					} finally {
						monitor.done();
					}
				}
			};
			PlatformUI.getWorkbench().getProgressService().run(true, true, op);
			if (errorMessages.toString().compareTo("")!=0)
				throw new Exception(errorMessages.toString());
		} catch (Exception ex) {
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", ex.getMessage());
			return false;
		}
		return true;
	}

}
